import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { showMessage } from './status';
import { IResponse } from './type';
import { getToken } from '/@/utils/auth';
import { TokenPrefix } from '/@/utils/auth';
import { ADMIN_USER_TOKEN, USER_TOKEN, BASE_URL } from '/@/store/constants';

// 请求缓存
const requestCache = new Map();

const service: AxiosInstance = axios.create({
  // baseURL: import.meta.env.BASE_URL + '',
  baseURL: BASE_URL + '',
  timeout: 10000, // 减少超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// axios实例拦截请求
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers.ADMINTOKEN = localStorage.getItem(ADMIN_USER_TOKEN);
    config.headers.TOKEN = localStorage.getItem(USER_TOKEN);

    // 添加请求时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }

    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

// axios实例拦截响应
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status == 200) {
      if (response.data.code == 0 || response.data.code == 200) {
        return response;
      } else {
        return Promise.reject(response.data);
      }
    } else {
      return Promise.reject(response.data);
    }
  },
  // 请求失败
  (error: any) => {
    console.log('请求失败:', error.message);
    
    // 网络错误处理
    if (error.code === 'ECONNABORTED') {
      console.log('请求超时');
    } else if (error.code === 'ERR_NETWORK') {
      console.log('网络连接失败');
    }
    
    if (error.response) {
      console.log('响应状态:', error.response.status);
      if (error.response.status == 404) {
        // todo
      } else if (error.response.status == 403) {
        // todo
      } else if (error.response.status == 500) {
        console.log('服务器内部错误');
      }
    } else {
      console.log('网络错误或CORS错误');
    }
    return Promise.reject(error);
  },
);

// 带缓存的请求函数
const requestWithCache = async <T = any>(config: AxiosRequestConfig, useCache = false): Promise<T> => {
  const cacheKey = `${config.method}_${config.url}_${JSON.stringify(config.params || {})}`;
  
  if (useCache && requestCache.has(cacheKey)) {
    const cached = requestCache.get(cacheKey);
    if (Date.now() - cached.timestamp < 5 * 60 * 1000) { // 5分钟缓存
      return cached.data;
    }
  }
  
  try {
    const response = await service.request<any, AxiosResponse<IResponse>>(config);
    const data = response.data;
    
    if (useCache) {
      requestCache.set(cacheKey, {
        data,
        timestamp: Date.now(),
      });
    }
    
    return data as T;
  } catch (error) {
    throw error;
  }
};

// 带重试的请求函数
const requestWithRetry = async <T = any>(config: AxiosRequestConfig, retries = 2): Promise<T> => {
  try {
    return await requestWithCache<T>(config);
  } catch (error) {
    if (retries > 0) {
      console.log(`请求失败，重试中... (剩余重试次数: ${retries})`);
      await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
      return requestWithRetry<T>(config, retries - 1);
    }
    throw error;
  }
};

const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  return requestWithRetry<T>(config);
};

export function get<T = any>(config: AxiosRequestConfig, useCache = false): Promise<T> {
  return requestWithCache<T>({ ...config, method: 'GET' }, useCache);
}

export function post<T = any>(config: AxiosRequestConfig): Promise<T> {
  return request<T>({ ...config, method: 'POST' });
}

// 清除缓存
export const clearCache = () => {
  requestCache.clear();
};

export default request;

export type { AxiosInstance, AxiosResponse };
